<template>
  <view class="container">
    <!-- Result Header -->
    <view :class="resultClass" class="result-header">
      <view class="result-icon">
        <uni-icons :type="resultIcon" color="#ffffff" size="60"></uni-icons>
      </view>
      <view class="result-title">{{ resultTitle }}</view>
      <view class="result-score">{{ scoreResult.score }}分</view>
      <view v-if="levelInfo" class="result-level">{{ levelInfo.levelName }}</view>
    </view>

    <!-- Score Summary -->
    <view class="score-summary">
      <view class="summary-item">
        <view class="summary-value">{{ scoreResult.correctCount }}/{{ scoreResult.totalQuestions }}</view>
        <view class="summary-label">答对题数</view>
      </view>
      <view class="summary-item">
        <view class="summary-value">{{ scoreResult.accuracy }}%</view>
        <view class="summary-label">正确率</view>
      </view>
      <view class="summary-item">
        <view class="summary-value">{{ formatTime(scoreResult.totalTime) }}</view>
        <view class="summary-label">总用时</view>
      </view>
      <view class="summary-item">
        <view class="summary-value">{{ formatTime(scoreResult.averageTime) }}</view>
        <view class="summary-label">平均用时</view>
      </view>
    </view>

    <!-- Score Breakdown -->
    <view class="score-breakdown">
      <view class="breakdown-title">分数构成</view>
      <view class="breakdown-item">
        <text class="breakdown-label">基础分数</text>
        <text class="breakdown-value">{{ scoreResult.baseScore }}分</text>
      </view>
      <view v-if="scoreResult.timeBonus > 0" class="breakdown-item">
        <text class="breakdown-label">时间奖励</text>
        <text class="breakdown-value">+{{ scoreResult.timeBonus }}分</text>
      </view>
      <view class="breakdown-item total">
        <text class="breakdown-label">总分</text>
        <text class="breakdown-value">{{ scoreResult.score }}分</text>
      </view>
    </view>

    <!-- Error Analysis -->
    <view v-if="scoreResult.errorAnalysis.totalErrors > 0" class="error-analysis">
      <view class="analysis-title">错误分析</view>
      <view class="analysis-content">
        <view class="error-stats">
          <text class="error-count">共{{ scoreResult.errorAnalysis.totalErrors }}道错题</text>
        </view>

        <view v-if="scoreResult.errorAnalysis.mostDifficultOperation" class="error-types">
          <view class="error-type-item">
            <text class="error-type-label">最容易出错的运算：</text>
            <text class="error-type-value">{{
                getOperationName(scoreResult.errorAnalysis.mostDifficultOperation)
              }}
            </text>
          </view>
        </view>

        <view v-if="scoreResult.errorAnalysis.mostDifficultValueType" class="error-types">
          <view class="error-type-item">
            <text class="error-type-label">最容易出错的类型：</text>
            <text class="error-type-value">{{
                getValueTypeName(scoreResult.errorAnalysis.mostDifficultValueType)
              }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- Suggestions -->
    <view v-if="suggestions.length > 0" class="suggestions">
      <view class="suggestions-title">练习建议</view>
      <view class="suggestion-list">
        <view
            v-for="(suggestion, index) in suggestions"
            :key="index"
            class="suggestion-item"
        >
          <uni-icons color="#007AFF" size="16" type="info"></uni-icons>
          <text class="suggestion-text">{{ suggestion }}</text>
        </view>
      </view>
    </view>

    <!-- Level Progress -->
    <view v-if="levelInfo && levelInfo.nextLevelScore" class="level-progress">
      <view class="progress-title">升级进度</view>
      <view class="progress-info">
        <text>距离{{ getNextLevelName(levelInfo.level) }}还需 {{ levelInfo.nextLevelScore - scoreResult.score }} 分
        </text>
      </view>
      <progress-bar
          :current-step="scoreResult.score"
          :show-info="false"
          :total-steps="levelInfo.nextLevelScore"
          color="#007AFF"
      ></progress-bar>
    </view>

    <!-- Action Buttons -->
    <view class="actions">
      <button class="action-btn secondary-btn" @tap="tryAgain">
        <uni-icons color="#007AFF" size="20" type="refresh"></uni-icons>
        <text>继续练习</text>
      </button>
      <button class="action-btn primary-btn" @tap="viewRecords">
        <uni-icons color="#ffffff" size="20" type="bars"></uni-icons>
        <text>查看记录</text>
      </button>
    </view>
  </view>
</template>

<script>
import ScoreCalculator from '@/utils/score-calculator.js';
import CommonUtils from '@/utils/common.js';
import Storage from '@/utils/storage.js';
import ProgressBar from '@/components/common/progress-bar.vue';

export default {
  components: {
    ProgressBar
  },
  data() {
    return {
      questions: [],
      totalTime: 0,
      settings: null,
      scoreResult: null,
      levelInfo: null,
      suggestions: []
    }
  },
  computed: {
    resultClass() {
      if (!this.scoreResult) return 'result-normal';
      if (this.scoreResult.isPerfect) return 'result-perfect';
      if (this.scoreResult.accuracy >= 90) return 'result-excellent';
      if (this.scoreResult.accuracy >= 80) return 'result-good';
      if (this.scoreResult.accuracy >= 60) return 'result-normal';
      return 'result-poor';
    },

    resultIcon() {
      if (!this.scoreResult) return 'info';
      if (this.scoreResult.isPerfect) return 'star-filled';
      if (this.scoreResult.accuracy >= 90) return 'medal';
      if (this.scoreResult.accuracy >= 80) return 'checkmarkempty';
      if (this.scoreResult.accuracy >= 60) return 'info';
      return 'closeempty';
    },

    resultTitle() {
      if (!this.scoreResult) return '练习完成';
      if (this.scoreResult.isPerfect) return '完美表现！';
      if (this.scoreResult.accuracy >= 90) return '表现优异！';
      if (this.scoreResult.accuracy >= 80) return '表现良好！';
      if (this.scoreResult.accuracy >= 60) return '继续努力！';
      return '还需加强练习';
    }
  },
  onLoad() {
    this.loadResultData();
  },
  methods: {
    // 加载结果数据
    loadResultData() {
      const maxWaitTime = 3000; // 最长等待时间3秒
      const checkInterval = 100; // 每100ms检查一次
      let elapsedTime = 0;

      const checkData = () => {
        const app = getApp();
        const resultData = app.globalData.speedCalcResult;

        if (resultData) {
          // 找到数据，处理数据
          this.questions = resultData.questions;
          this.totalTime = resultData.totalTime;
          this.settings = resultData.settings;

          this.calculateScore();
          this.calculateLevel();
          this.generateSuggestions();
          this.saveRecord();

          // 清除全局数据
          app.globalData.speedCalcResult = null;
          return;
        }

        elapsedTime += checkInterval;

        if (elapsedTime < maxWaitTime) {
          // 继续等待
          setTimeout(checkData, checkInterval);
        } else {
          // 超时，显示错误
          uni.showModal({
            title: '提示',
            content: '未找到练习数据',
            showCancel: false,
            success: () => {
              this.backToHome();
            }
          });
        }
      };

      checkData();
    },

    // 计算分数
    calculateScore() {
      this.scoreResult = ScoreCalculator.calculateSpeedCalcScore(this.questions, this.totalTime);
    },

    // 计算级别
    calculateLevel() {
      this.levelInfo = ScoreCalculator.calculateLevel(this.scoreResult.score, this.scoreResult.accuracy);
    },

    // 生成建议
    generateSuggestions() {
      this.suggestions = ScoreCalculator.generateSuggestions(this.scoreResult);
    },

    // 保存记录
    saveRecord() {
      const record = {
        type: 'speed-calc',
        questionCount: this.scoreResult.totalQuestions,
        correctCount: this.scoreResult.correctCount,
        accuracy: this.scoreResult.accuracy,
        totalTime: this.scoreResult.totalTime,
        averageTime: this.scoreResult.averageTime,
        score: this.scoreResult.score,
        baseScore: this.scoreResult.baseScore,
        timeBonus: this.scoreResult.timeBonus,
        isPerfect: this.scoreResult.isPerfect,
        level: this.levelInfo.level,
        levelName: this.levelInfo.levelName,
        settings: this.settings,
        errorAnalysis: this.scoreResult.errorAnalysis,
        questions: this.questions.map(q => ({
          question: q.question,
          answer: q.answer,
          userAnswer: q.userAnswer,
          isCorrect: q.isCorrect,
          timeUsed: q.timeUsed,
          operation: q.operation,
          valueType: q.valueType
        }))
      };

      Storage.saveSpeedCalcRecord(record);
    },

    // 格式化时间
    formatTime(seconds) {
      return CommonUtils.formatTime(seconds);
    },

    // 获取运算名称
    getOperationName(operation) {
      const names = {
        'add': '加法',
        'subtract': '减法',
        'multiply': '乘法',
        'divide': '除法'
      };
      return names[operation] || operation;
    },

    // 获取数值类型名称
    getValueTypeName(valueType) {
      const names = {
        'integer': '整数',
        'decimal': '小数',
        'percentage': '百分数'
      };
      return names[valueType] || valueType;
    },

    // 获取下一级别名称
    getNextLevelName(currentLevel) {
      const levels = {
        'beginner': '中级',
        'intermediate': '高级',
        'advanced': '专家',
        'expert': '大师'
      };
      return levels[currentLevel] || '更高级别';
    },

    // 继续练习
    tryAgain() {
      uni.navigateTo({
        url: `/pages/speed-calc/practice?settings=${encodeURIComponent(JSON.stringify(this.settings))}`
      });
    },

    // 查看记录
    viewRecords() {
      uni.switchTab({
        url: '/pages/speed-calc/records'
      });
    },

    // 返回首页
    backToHome() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.result-header {
  padding: 60rpx 40rpx 40rpx;
  text-align: center;
  color: white;
  position: relative;

  &.result-perfect {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }

  &.result-excellent {
    background: linear-gradient(135deg, #a0f0ed 0%, #67e8f9 100%);
  }

  &.result-good {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  }

  &.result-normal {
    background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  }

  &.result-poor {
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  }

  .result-icon {
    margin-bottom: 20rpx;
  }

  .result-title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 15rpx;
  }

  .result-score {
    font-size: 48rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
  }

  .result-level {
    font-size: 24rpx;
    opacity: 0.9;
  }
}

.score-summary {
  display: flex;
  background: white;
  margin: 30rpx 40rpx;
  border-radius: 15rpx;
  padding: 30rpx 20rpx;
  box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);

  .summary-item {
    flex: 1;
    text-align: center;

    .summary-value {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 8rpx;
    }

    .summary-label {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.score-breakdown,
.error-analysis,
.suggestions,
.level-progress {
  background: white;
  margin: 0 40rpx 30rpx;
  border-radius: 15rpx;
  padding: 30rpx;
  box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);
}

.breakdown-title,
.analysis-title,
.suggestions-title,
.progress-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 25rpx;
}

.breakdown-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  &.total {
    font-weight: bold;
    color: #007AFF;
    border-top: 2rpx solid #f0f0f0;
    margin-top: 10rpx;
    padding-top: 20rpx;
  }

  .breakdown-label {
    font-size: 28rpx;
    color: #666;
  }

  .breakdown-value {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
  }
}

.analysis-content {
  .error-stats {
    margin-bottom: 20rpx;

    .error-count {
      font-size: 28rpx;
      color: #dc3545;
      font-weight: bold;
    }
  }

  .error-types {
    .error-type-item {
      display: flex;
      margin-bottom: 15rpx;

      .error-type-label {
        font-size: 26rpx;
        color: #666;
        margin-right: 10rpx;
      }

      .error-type-value {
        font-size: 26rpx;
        color: #dc3545;
        font-weight: bold;
      }
    }
  }
}

.suggestion-list {
  .suggestion-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .suggestion-text {
      flex: 1;
      font-size: 26rpx;
      color: #666;
      line-height: 1.4;
      margin-left: 15rpx;
    }
  }
}

.progress-info {
  margin-bottom: 20rpx;
  text-align: center;

  text {
    font-size: 26rpx;
    color: #666;
  }
}

.actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: white;
  box-shadow: 0 -5rpx 15rpx rgba(0, 0, 0, 0.1);
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;

  &.secondary-btn {
    background-color: #f8f9fa;
    color: #007AFF;
    border: 2rpx solid #007AFF;
  }

  &.primary-btn {
    background: linear-gradient(135deg, #67e8f9, #38bdf8);
    color: white;
  }

  &:active {
    transform: scale(0.98);
  }
}
</style>